<template>
  <div style="width: 100%;height: 100vh;color:var(--color-neutral-10);margin: 0 auto">
      <div style="padding: 40px 0 0 0;margin: 0 auto;max-width: 1550px;width: 90%;">
        <p style="font-size: 24px;font-weight: bold;margin-bottom: 20px">账号管理</p>
      </div>
      <div style="width: 100%;height: calc(100% - 96px);position: relative;overflow-y: auto;padding-bottom: 60px;">
        <div style="width: 90%;height: 100%;margin: 0 auto;max-width: 1550px;padding-top: 20px;">
                
          <div style="margin-bottom: 20px;width: 100%;position: relative">
          <a-input :disabled="data.loading" v-model="data.form.email" style="border: 0px;line-height: 36px;display: inline-block;width: 200px;margin-right: 10px;background-color: transparent;border-bottom: 1px solid var(--color-neutral-10)" placeholder="用户邮箱"></a-input>
          <v-btn :loading="data.loading" style="margin-right: 10px" variant="text"
                 @click="data.form.page=1;getTable()"
          >搜索/刷新</v-btn>
          <v-btn :disabled="data.loading" style="margin-right: 10px" variant="text"
                 @click="()=>{
                  data.showAddUserForm = true
                  data.addUserForm.email = ''
                  data.addUserForm.name = ''
                  data.addUserForm.inputPassword = ''
                 }"
          >添加咨询师账号</v-btn>
          <div v-if="data.form.total>data.form.size" style="display: inline-block;float: right;">
            <v-btn variant="text" @click="data.form.page=1;getTable()" :disabled="data.loading || data.form.page==1" style="margin-left: 5px;">第一页</v-btn>
            <v-btn variant="text" @click="data.form.page-=1;getTable()" :disabled="data.loading || data.form.page==1" style="margin-left: 5px">上一页</v-btn>
            <a-trigger trigger="click" :unmount-on-close="false">
              <v-btn variant="text" :disabled="data.loading" style="margin-left: 5px">{{ data.form.page.toString() + '/' + data.form.pageTotal.toString() }}</v-btn>
              <template #content>
                <div style="padding: 20px 20px;border-radius: 10px;background-color: var(--color-neutral-1);box-shadow: 0 4px 10px rgba(0,0,0,0.1)">
                  <a-input v-model="data.form.pageInput" placeholder="页码" style="width: 70px;"></a-input><a-button :loading="data.loading" @click="tableChangePage" :disabled="data.form.pageInput==''" style="margin-left: 5px">转到</a-button>
                  <br>
                  <p v-if="data.form.warningText!=''" style="color: red">{{ data.form.warningText }}</p>
                </div>
              </template>
            </a-trigger>
            <v-btn variant="text" @click="data.form.page+=1;getTable()" :disabled="data.loading || data.form.page==data.form.pageTotal" style="margin-left: 5px">下一页</v-btn>
            <v-btn variant="text" @click="data.form.page=data.form.pageTotal;getTable()" :disabled="data.loading || data.form.page==data.form.pageTotal" style="margin-left: 5px">最后一页</v-btn>
          </div>
        </div>
        <a-table @row-click="tableRowClick" :pagination="false" :loading="data.loading" style="width: 100%;margin-bottom: 40px;" :columns="[
  { dataIndex: 'mark', title: '标记' },
  { dataIndex: 'email', title: '邮箱' },
  { dataIndex: 'name', title: '姓名' },
  { dataIndex: 'avatar', title: '头像' },
  { dataIndex: 'province', title: '省份' },
  { dataIndex: 'subjectType', title: '选科类型' },
  { dataIndex: 'score', title: '高考分数' },
  { dataIndex: 'ranks', title: '高考位次' },
  { dataIndex: 'isSM', title: '为色盲' },
  { dataIndex: 'isSR', title: '为色弱' },
  { dataIndex: 'isVIP', title: '为VIP' },
  { dataIndex: 'password', title: '登录密码' },
  { dataIndex: 'type', title: '为咨询师' },
]" :data="data.table" />

        </div>
      </div>
    </div>
  <a-modal v-model:visible="data.showEditaccountInfoForm" @ok="changeaccountInfo" :closable="data.isSaving==false" :mask-closable="data.isSaving==false" :ok-loading="data.isSaving">
    <template #title>
      编辑账号信息
    </template>
    <div style="max-height: calc(80vh - 48px - 65px - 40px);overflow-y: scroll">
      <v-btn @click="deleteSingle" style="margin:0 auto;display: block;" variant="text">删除此账号</v-btn>
      <data-editor :read-only="data.isSaving==true" @dataChanged="accountInfoChanged" style="color: var(--color-neutral-10);width: 100%;background-color: white;border-radius: 5px;padding: 15px 15px 5px 15px;margin-top: 10px;" v-if="data.showEditaccountInfoForm" :data="data.editaccountInfoSelectedItem"></data-editor>
    </div>
  </a-modal>

  <div v-if="data.showAddUserForm==true" style="width: 100vw;height: 100vh;padding-left: 50vw;padding-top: 50vh;background-color: rgba(0,0,0,0.3);position: fixed;left: 0;top: 0;">
    <div style="transform: translate(-50%,-50%);background-color: var(--color-neutral-1);border-radius: 10px;box-shadow: 0 4px 10px rgba(0,0,0,0.1);color: var(--color-neutral-10);display: inline-block;">
      <div style="width: 100%;position: relative;padding: 20px 20px;padding-bottom: 10px;">
        <span style="font-size: 18px;font-weight: bold;">添加咨询师账号</span>
        <svg v-if="data.isSaving==false" @click="()=>{
          data.showAddUserForm = false
        }" style="float: right;cursor: pointer;" width="24" height="24" viewBox="0 0 48 48" fill="currentColor"><path fill-rule="evenodd" clip-rule="evenodd" d="M23.886 20.957L37.32 7.522a1 1 0 011.414 0l1.414 1.414a1 1 0 010 1.415L26.714 23.786 40.149 37.22a1 1 0 010 1.414l-1.414 1.414a1 1 0 01-1.414 0L23.886 26.614 10.45 40.049a1 1 0 01-1.415 0l-1.414-1.414a1 1 0 010-1.414l13.435-13.435L7.622 10.35a1 1 0 010-1.415l1.414-1.414a1 1 0 011.415 0l13.435 13.435z" fill="currentColor"/></svg>
      </div>
      <div style="width: 400px;max-height: calc(80vh - 48px - 65px - 40px);overflow-y: scroll;padding: 20px 20px;">
        <v-text-field :disabled="data.isSaving" v-model="data.addUserForm.email" label="邮箱" variant="outlined"></v-text-field>
        <v-text-field :disabled="data.isSaving" v-model="data.addUserForm.name" label="姓名" variant="outlined"></v-text-field>
        <v-text-field :disabled="data.isSaving" v-model="data.addUserForm.inputPassword" label="登录密码" variant="outlined"></v-text-field>
        <p v-if="data.addUserForm.warningText!=''" style="color: red;">{{ data.addUserForm.warningText }}</p>
        <div style="text-align: right;">
          <button @click="data.showAddUserForm = false" style="margin-right: 10px;">取消</button>
          <button @click="addUser">确定</button>
        </div>
      </div>
    </div>
  </div>
  <!-- <a-modal v-model:visible="data.showAddUserForm" @ok="addUser" :closable="data.isSaving==false" :mask-closable="data.isSaving==false" :ok-loading="data.isSaving">
    <template #title>
      添加咨询师账号
    </template>
    <div style="max-height: calc(80vh - 48px - 65px - 40px);overflow-y: scroll;padding-top: 10px;">
      
    </div>
  </a-modal> -->
</template>

<script>
import tool from '@/utlis/tool'
import config from '@/config'
import dataEditor from "@/components/dataEditor.vue";
import axios from "axios";
import { sha256 } from 'js-sha256';

export default {
  components:{
    dataEditor
  },
  name: '',
  data() {
    return {
      data:{
        loading:false,
        form:{
          page:1,
          size:25,
          total:0,
          pageTotal:0,
          pageInput:'',
          warningText:'',
          email:''
        },
        table:[],
        showEditaccountInfoForm:false,
        editaccountInfoSelectedItem:undefined,
        editaccountInfoSelectedItemMark:undefined,
        isSaving:false,

        showAddUserForm:false,
        addUserForm:{
          email:'',
          name:'',
          province:'',
          subjectType:'',
          ranks:0,
          score:0,
          isSM:0,
          isSR:0,
          isVIP:1,
          password:'',
          inputPassword:'',
          warningText:'',
          type:1
        }
      }
    }
  },

  methods: {
    async addUser(){
      this.data.addUserForm.warningText = ''
      if(this.data.addUserForm.email==''){
        this.data.addUserForm.warningText = '请输入邮箱'
        return
      }
      if(this.data.addUserForm.name==''){
        this.data.addUserForm.warningText = '请输入姓名'
        return
      }
      if(this.data.addUserForm.inputPassword==''){
        this.data.addUserForm.warningText = '请输入登录密码'
        return
      }
      this.data.addUserForm.password = this.data.addUserForm.inputPassword
      this.data.isSaving = true
      let re = await tool.axiosPostWithCheckStatus(config.serverURL,'/user/register',this.data.addUserForm)
      this.data.isSaving = false
      if(re.status!=1){
        this.data.addUserForm.warningText = re.content
        return
      }
      this.getTable()
      this.data.showAddUserForm = false
    },
    async deleteSingle(){
      this.data.isSaving = true
      await tool.axiosPostWithCheckStatus(config.serverURL,'/bg/account/delete',{
        token:this.bgData.loginedAdminInfo.token,
        mark:this.data.editaccountInfoSelectedItemMark
      })
      this.data.isSaving = false
      this.data.showEditaccountInfoForm = false
      this.getTable()
    },
    async changeaccountInfo(){
      this.data.isSaving = true
      this.data.editaccountInfoSelectedItem['mark'] = this.data.editaccountInfoSelectedItemMark.toString()
      this.data.editaccountInfoSelectedItem['subjects'] = JSON.stringify(this.data.editaccountInfoSelectedItem['subjects'])
      this.data.editaccountInfoSelectedItem['allowChatUserEmails'] = JSON.stringify(this.data.editaccountInfoSelectedItem['allowChatUserEmails'])
      this.data.editaccountInfoSelectedItem['name'] = this.data.editaccountInfoSelectedItem['name'].toString()
      // const data = tool.encodeString(JSON.stringify({
      //   token:this.bgData.loginedAdminInfo.token,
      //   item:this.data.editaccountInfoSelectedItem
      // }))
      await tool.axiosPostWithCheckStatus(config.serverURL,'/bg/account/change',{
        token:this.bgData.loginedAdminInfo.token,
        item:this.data.editaccountInfoSelectedItem
      })
      // const file = new Blob([data], { type: 'text/plain' });
      // const formData = new FormData();
      // formData.append('file', file, 'filename.txt');
      // await axios.post(config.serverURL + '/bg/account/change', formData, {
      //   headers: {
      //     'Content-Type': 'multipart/form-data'
      //   }
      // }).then(response => {
      //   console.log(response)
      // })
      this.data.isSaving = false
      this.getTable()
    },
    accountInfoChanged(data){
      this.data.editaccountInfoSelectedItem = JSON.parse(JSON.stringify(data)).data
    },
    tableRowClick(data){
      for(let i=0;i<Object.keys(data).length;i++){
        try{
          data[Object.keys(data)[i]] = JSON.parse(data[Object.keys(data)[i]])
        }catch (e){

        }
      }
      data = JSON.parse(JSON.stringify(data))
      this.data.editaccountInfoSelectedItemMark = data.mark
      delete data['mark']
      this.data.editaccountInfoSelectedItem = data
      this.data.showEditaccountInfoForm = true
    },
    async deleteAll(){
      this.data.loading = true
      await tool.axiosPostWithCheckStatus(config.serverURL,'/bg/account/delete',{
        token:this.bgData.loginedAdminInfo.token
      })
      this.data.loading = false
      this.data.form.page = 1
      this.getTable()
    },
    tableChangePage(){
      this.data.form.warningText=''
      let a = parseInt(this.data.form.pageInput)
      if(isNaN(a)){
        this.data.form.warningText='页码应为数字'
        return
      }else{
        if(a<1 || a>this.data.form.pageTotal){
          this.data.form.warningText='页码应在1到' + this.data.form.pageTotal.toString() + '之间'
          return
        }
        this.data.form.page = a
        this.getTable()
      }
    },
    imported(){
      this.getTable()
    },
    async getTable(){
      this.data.loading = true
      let re = (await tool.axiosPostWithCheckStatus(config.serverURL,'/bg/account/list',{
        token:this.bgData.loginedAdminInfo.token,
        page:this.data.form.page,
        size:this.data.form.size,
        email:this.data.form.email
      }))
      this.data.form.total = re.results.total
      this.data.form.pageTotal = tool.getPageTotal(re.results.total,this.data.form.size)
      this.data.table = re.results.data
      this.data.loading = false
    }
  },

  //生命周期 - 挂载完成（可以访问DOM元素）",html模板已渲染
  mounted() {
    this.getTable()
  },

  props: {
    appData:undefined,
    bgData:undefined
  },

  //监听属性 类似于data概念",
  computed: {},

  //监控data中的数据变化",
  watch: {},

  //生命周期 - 创建完成（可以访问当前this实例）",数据模型已加载，方法已加载,html模板已加载,html模板未渲染
  created() {
  },

  //生命周期 - 挂载之前",html模板未渲染
  beforeMount() {
  },

  //生命周期 - 更新之前",数据模型已更新,html模板未更新
  beforeUpdate() {
  },

  // 生命周期 - 销毁之前调用
  beforeDestroy() {
  },

  //生命周期 - 更新之后",数据模型已更新,html模板已更新
  updated() {
  },

  //生命周期 - 销毁完成"
  destroyed() {
  },

  //如果页面有keep-alive缓存功能，这个函数会触发",
  activated() {
  }
}
</script>

<style scoped>

</style>